package com.ruoyi.web.controller.report;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.report.domain.ReportShareToken;
import com.ruoyi.report.domain.ReportWorkbookData;
import com.ruoyi.report.domain.dto.ShareTokenDto;
import com.ruoyi.report.service.IReportShareTokenService;
import com.ruoyi.report.service.IReportWorkbookDataService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
 * @version v1.0
 * @ProjectName: report
 * @ClassName: ReportShareController
 * @Description: TODO(一句话描述该类的功能)
 * @Author: 王莹
 * @Date: 2022/3/23 8:54
 */
@RestController
@RequestMapping("/report/share")
public class ReportShareController {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private IReportShareTokenService reportShareTokenService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private IReportWorkbookDataService reportWorkbookDataService;

    @PostMapping("/create")
    public AjaxResult viewerLogin(@RequestBody ShareTokenDto shareTokenDto)
    {
        AjaxResult ajax = AjaxResult.success();

        // ExpireTime的时间颗粒度：分钟
        Long time = shareTokenDto.getTime() * 24 * 60;
        // 生成令牌
        String token = sysLoginService.viewerLogin(time);
        String id = UUID.randomUUID().toString().replaceAll("-", "");

        ReportShareToken shareTokenLog = new ReportShareToken();
        shareTokenLog.setId(id);
        shareTokenLog.setReportId(shareTokenDto.getReportId());
        shareTokenLog.setReportName(shareTokenDto.getReportName());
        shareTokenLog.setExtractionNumber(shareTokenDto.getNumber());
        shareTokenLog.setEffectiveTime(shareTokenDto.getTime());
        shareTokenLog.setTokenStr(token);
        shareTokenLog.setSenderId(SecurityUtils.getUsername());
        SysUser user = userService.selectUserByUserName("viewer");
        shareTokenLog.setCreateBy(user.getUserName());
        Date date1 = new Date();
        shareTokenLog.setCreateTime(new Date());
        date1.setTime(System.currentTimeMillis() + (Long.valueOf(time) * 60L * 1000L));
        shareTokenLog.setExpirationTime(date1);

        reportShareTokenService.insertReportShareToken(shareTokenLog);

        List<ReportWorkbookData> index = reportWorkbookDataService.selectReportSheetIndexByReportId(Long.parseLong(shareTokenDto.getReportId()));

        ajax.put(Constants.TOKEN, token);
        ajax.put("id", id);
        ajax.put("index", index);
        ajax.put("reportId", shareTokenDto.getReportId());

        return ajax;
    }

}
